package datasource.temp;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDStream;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

public class PDFModifier {
    public void removeTextFromPDF(String inputPath, String outputPath, String textToRemove) throws IOException {
        try (PDDocument document = PDDocument.load(new File(inputPath))) {
            TextRemover textRemover = new TextRemover();
            textRemover.setTextToRemove(textToRemove);

            PDFContentProcessor processor = new PDFContentProcessor(textRemover);

            for (PDPage page : document.getPages()) {
                processor.processPage(page);

                PDStream newContentStream = new PDStream(document);
                try (OutputStream outputStream = newContentStream.createOutputStream();
                     PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.OVERWRITE, true, true)) {
                    processor.writeTo(contentStream);
                }
                page.setContents(newContentStream);
            }
            document.save(outputPath);
        }
    }
}
